#!/bin/sh /etc/rc.common
#
# Copyright (C) 2018 Lean <coolsnowwolf@gmail.com>
#

START=99

start()
{
	local vt_enabled=`uci get ipsec.@service[0].enabled 2>/dev/null`
	local vt_clientip=`uci get ipsec.@service[0].clientip`
	local vt_clientdns=`uci get ipsec.@service[0].clientdns`
	local vt_account=`uci get ipsec.@service[0].account`
	local vt_password=`uci get ipsec.@service[0].password 2>/dev/null`
	local vt_secret=`uci get ipsec.@service[0].secret 2>/dev/null`

	# -----------------------------------------------------------------
	if [ "$vt_enabled" = 0 ]; then
    /etc/init.d/ipsec disable && /etc/init.d/ipsec stop
		echo "WARNING: IPSec VPN is disabled."
		return 1
	fi

	cat > /etc/ipsec.conf <<EOF
# ipsec.conf - strongSwan IPsec configuration file

# basic configuration

config setup
    # strictcrlpolicy=yes
    uniqueids=never

# Add connections here.

conn xauth_psk
	keyexchange=ikev1
	ike=aes128-sha1-modp2048,3des-sha1-modp1536
  esp=aes128-sha1,3des-sha1
	left=%defaultroute
	leftauth=psk
	leftsubnet=0.0.0.0/0
	right=%any
	rightauth=psk
	rightauth2=xauth
	rightsourceip=$vt_clientip
	rightdns=$vt_clientdns
	auto=add
EOF

	cat > /etc/ipsec.secrets <<EOF
# /etc/ipsec.secrets - strongSwan IPsec secrets file
: PSK "$vt_secret"
$vt_account : XAUTH "$vt_password"
EOF

/etc/init.d/ipsec enable && /etc/init.d/ipsec start
echo "IPSec VPN is Started."

}

stop() {
  /etc/init.d/ipsec disable && /etc/init.d/ipsec stop
	echo "IPSec VPN is Stopped."
}

restart() {
  stop
  start
}


